/**
 * Writed by yura and mak
 */

package wz.legend.handlers.info;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.log4j.Logger;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.handlers.ResponseHandler;
import wz.legend.util.ParseUtils;
import wz.legend.util.UriConstants;
import wz.legend.util.Utils;


public class AreaInfoHandler implements ResponseHandler {
    private static final Logger LOG = Logger.getLogger(AreaInfoHandler.class);

    public void handle(HttpContext httpContext, Context context) {
        URI uri = null;
        try {
            uri = new URI(httpContext.getRequest().getRequestLine().getUri());
            if (uri.getRawPath().contains(UriConstants.AREA_PHP)
                    || uri.getRawPath().contains(UriConstants.MAIN_FRAME)) {
                String content = Utils.getResponseContent(httpContext);
                int areaTime = ParseUtils.parseAreaTime(content);
                String areaName = ParseUtils.parseAreaName(content);

                List<String> crossList = ParseUtils.parseCross(content);

                LOG.debug("Area " + areaName + " time=" + areaTime);

                context.addProperty(InfoConstants.AREA_NAME, areaName);
                context.addProperty(InfoConstants.AREA_TIME, areaTime);
                context.addProperty(InfoConstants.AREA_CROSS, crossList);
            }
        } catch (URISyntaxException e) {
            LOG.error(e.toString());
        } catch (IndexOutOfBoundsException e) {
            LOG.error(e.toString());
        } catch (Exception e) {
            LOG.error(uri.toString(), e);
        }
    }
}
